# coding=utf-8
import os
from flask import url_for

from apps.a_common.log import MyLogger
from config import HOST, IMAGE_RESIZE_HEIGHT
from utils.time import timer

logger = MyLogger('storage')
IMAGE_FORMAT = 'storage/image/{}'

"""####################################### INTERFACE WITH OSS #######################################"""


@timer
def post_file_to_storage(name, data):
    name = IMAGE_FORMAT.format(name)
    if hasattr(data, 'read'):
        byte_data = data.read()
    elif hasattr(data, '__iter__'):
        byte_data = data
    else:
        raise Exception()
    with open(name, 'wb') as f:
        f.write(byte_data)
    logger.info(f'save {len(byte_data) // 1024} kb data, name: {name}')
    return name


@timer
def get_file_from_storage(name, size=IMAGE_RESIZE_HEIGHT):
    with open(name, 'rb') as f:
        byte_data = f.read()
    logger.info(f'save {len(byte_data) // 1024} kb data, name: {name}')
    return byte_data


@timer
def rename_file(old_name, new_name):
    os.rename(old_name, new_name)


def get_file_download_url(name: str):
    return HOST + url_for('files._get_image', image_url=name)


def get_key_from_url(url: str):
    prefix = HOST + url_for('files._get_image', image_url='')[: -1]  # 两个 -1 都是为了去掉末尾的 /
    key = url.replace(prefix, '')
    if key.endswith('/'):
        key = key[:-1]
    return key
